c++ class “xxxx“ does not name a type是怎么一回事 | 您所在的位置:网站首页 › 结构体does not name a type › c++ class “xxxx“ does not name a type是怎么一回事 |
declare class does not name a type 出现这个编译错误主要有四个可能原因,现总结如下: 1.引用的类命名空间未包含 2.引用的类头文件未包含 3.包含了头文件,或者已经前置声明了,则说明所引用的类名写错。 4.循环引用头文件 前置声明要素: 1.前置声明需要注意以上提到的四点 2.尽可能的采用前置声明(做到只有包含继承类的头文件) 3.使用前置声明时,cpp文件中include 头文件次序必须先 包含前置声明的类定义头文件,再包含本类头文件。 否则会出现如下编译错误. (expected constructor, destructor, or type conversion before ‘typedef') https://blog.csdn.net/typename/article/details/7173550 原因二 前置声明 XXX应该是一种用户定义的数据类型,而由于没有声明或者拼写错误或者与关键词重名,导致编译有错,出现类型错误。 在一个源文件中,要声明或定义一个类的指针时,必须在使用前声明或定义该类,因此下面的代码会报错:class A{public: B *b;};class B{public: A *a;};int main(){ return 0;}12345678910111213141516 报错为“error: ‘B’ does not name a type”,就是因为在A类中使用B *b之前没有声明或定义B类,如果在第一行加上一句前置声明(forward declaration)“class B;”,就不会有这样的问题了。
class appv_forward; //forward declaration 前置声明 class obu_data_channel_t { public: 而在头文件互相包含时,也会引发“error: ‘xxx’ does not name a type”,其报错原因和上面的代码是相同的, 请看下面的代码:a.h: #ifndef A_H_INCLUDED #define A_H_INCLUDED #include "b.h" class A{ public: B *b; }; #endif // A_H_INCLUDEDb.h: #ifndef B_H_INCLUDED #define B_H_INCLUDED #include "a.h" class B{ public: A *a; }; #endif // B_H_INCLUDED main.cpp: #include "a.h" #include "b.h" int main() { return 0; }
编译就会报错:“error: ‘A’ does not name a type”。 预处理命令为“gcc -E -o a.i a.h”: # 1 "a.h"# 1 ""# 1 ""# 1 "a.h"# 1 "b.h" 1# 1 "a.h" 1# 5,"b.h" 2class B{public: A *a;}; # 5 "a.h" 2class A{public: B *b;};1234567891011121314151617181920212223242526。 |
CopyRight 2018-2019 实验室设备网 版权所有 |